package com.superbit.web.servlet;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.superbit.web.utils.JsonResponseUtil;

import net.sf.json.JSONObject;

/** @author  WangZhenwei 
  * @date 创建时间：2018年1月20日 下午6:13:53  
  * @descrip 
  */
@ResponseBody
@RequestMapping("/userImg.act")
public class UserImgController {

	/**
	 * 上传图片
	 * @throws IOException 
	 */
	@RequestMapping(params = "cmd=uploadPic")
	public String uploadPic(MultipartFile pic, HttpServletRequest req, HttpServletResponse resp) throws IOException{
		// 1.防止附件重名
		DateFormat df = new SimpleDateFormat();
		String newFileName = df.format(new Date());
		Random random = new Random();
		for (int i = 0; i < 3; i++) {
			newFileName += random.nextInt(10);
		}
		String ext = FilenameUtils.getExtension(pic.getOriginalFilename());
		newFileName += "." + ext;
		// 2.将附件上传至指定服务器的位置
		String realPath = req.getSession().getServletContext().getRealPath("");
		String imgUrl = "\\upload\\" + newFileName;//图片的相对路径
		String allUrl = realPath + imgUrl;
		// 3.图片上传
		pic.transferTo(new File(allUrl));
		
		// 4.图片回显
		JSONObject obj = new JSONObject();
		obj.put("allUrl", imgUrl);
		obj.put("imgUrl", imgUrl);
		
		resp.setContentType("application/json;charset=UTF-8");
		resp.getWriter().write(obj.toString());
		return null;
		
	}
}
